package com.th.apicenter.rta.service;

import com.th.apicenter.rta.proto.BaiduRtaApiRequestProtobuf;
import com.th.apicenter.rta.proto.KSProtobuf;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@Slf4j
public class BaiduRTAService {

    public void receiveRTA(BaiduRtaApiRequestProtobuf.RtaApiRequest rtaApiRequest) {
        log.info("baidu RTA 得到的数据：{}", rtaApiRequest);
        String url = "https://promotion-partner.kuaishou.com/rest/n/rta/common/kfy";  // 测试环境
        String requestId = "00000298d27e48be9d4bb2180395357b";  // 请求Id
        String channel = "SZTH";  // 渠道标识，需向快手技术申请
        String token = "p9r4m1f5x2";  // 渠道标识令牌
        CloseableHttpClient client = HttpClients.createDefault();

        try {
            KSProtobuf.RtaRequest.Builder builder = KSProtobuf.RtaRequest.newBuilder();
            builder.setRequestId(requestId);
            builder.setChannel(channel);
            long requestTime = System.currentTimeMillis();
            builder.setRequestTime(requestTime);
            String sign = requestId + requestTime + token;
            String signKey = DigestUtils.md5Hex(sign).toLowerCase();
            builder.setSign(signKey);

            KSProtobuf.RtaRequest.Device.Builder deviceBuilder = KSProtobuf.RtaRequest.Device.newBuilder();
            deviceBuilder.setIdfa(rtaApiRequest.getDeviceInfo().getIdfa().toStringUtf8());
            deviceBuilder.setIdfaMd5(rtaApiRequest.getDeviceInfo().getIdfaMd5().toStringUtf8());
            builder.setDevice(deviceBuilder.build());
            String promotionType = "kwai_lite_laxin";
            builder.addPromotionType(promotionType);

            HttpPost request = new HttpPost(url);
            request.addHeader("content-type", "application/x-protobuf");
            request.setEntity(new ByteArrayEntity(builder.build().toByteArray()));
            try (CloseableHttpResponse response = client.execute(request)) {
                System.out.println("\n=== Response Status ===");
                System.out.println("Status: " + response.getStatusLine());

                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 3. 解析Protobuf响应 (使用KSProtobuf)
                    byte[] responseBytes = EntityUtils.toByteArray(entity);
                    KSProtobuf.RtaResponse rtaResponse = KSProtobuf.RtaResponse.parseFrom(responseBytes);

                    System.out.println("\n=== Response Body (Protobuf) ===");
//                    System.out.println("是否允许投放: " + rtaResponse);
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
